import type { FC } from 'react'
import { useLayoutEffect } from 'react'
import { Button, Form, Select } from 'antd'
import { useLoaderData, useSearchParams, useAsyncValue } from 'react-router-dom'

const ArticleListSearch: FC = () => {
  const loaderData = useLoaderData() as { q: ArtListQuery }
  const [formRef] = Form.useForm()
  const [, setSearchParams] = useSearchParams()
  const asyncValue = useAsyncValue() as [BaseResponse<CateItem[]>, ArticleListResponse]

  useLayoutEffect(() => {
    if (loaderData?.q) {
      formRef.setFieldsValue(loaderData.q)
    }
  }, [loaderData?.q, formRef])

  const onFinish = (values: ArtListQuery) => {
    console.log('Success:', values)
    const params = { ...loaderData?.q, ...values, pagenum: 1 } as unknown as { [x: string]: string }
    setSearchParams(params)
  }

  return (
    <Form form={formRef} layout="inline" onFinish={onFinish} autoComplete="off">
      <Form.Item label="分类" name="cate_id">
        <Select
          style={{ width: 180 }}
          placeholder="请选择"
          options={[{ cate_name: '请选择', id: '' }, ...(asyncValue[0].data || [])]}
          fieldNames={{ label: 'cate_name', value: 'id' }}
        />
      </Form.Item>

      <Form.Item label="状态" name="state">
        <Select
          style={{ width: 180 }}
          placeholder="请选择"
          options={[
            { value: '', label: '请选择' },
            { value: '草稿', label: '草稿' },
            { value: '已发布', label: '已发布' }
          ]}
        />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          搜索
        </Button>
      </Form.Item>

      <Form.Item>
        <Button onClick={() => setSearchParams()}>重置</Button>
      </Form.Item>
    </Form>
  )
}

export default ArticleListSearch
